import { ref, computed, reactive } from 'vue'
import { defineStore } from 'pinia'

export const useAdminStore = defineStore(
    //id
    'admin',
    //定义初始值
    () => {
        //定义token
        const token = ref('')
        //获取token
        const getToken = computed(() => token.value)
        //保存token
        const saveToken = (t) => {
            token.value = t
        }
        //定义admin信息
        const admin = reactive({
            username: '',
            realName: '',
            avatar: '',
            adminId: 0
        })
        //保存admin信息
        const saveAdmin = (myAdmin) => {
            admin.username = myAdmin.username
            admin.realName = myAdmin.realName
            admin.avatar = myAdmin.imagePath || myAdmin.avatar
            admin.adminId = myAdmin.id || myAdmin.adminId
        }
        
        //设置管理员信息（兼容不同数据结构）
        const setAdminInfo = (userInfo) => {
            if (userInfo) {
                admin.username = userInfo.username || userInfo.name || ''
                admin.realName = userInfo.realName || userInfo.nickname || userInfo.username || ''
                admin.avatar = userInfo.avatar || userInfo.imagePath || ''
                admin.adminId = userInfo.id || userInfo.adminId || 0
            }
        }

        //要返回token，因为持久化token常量
        return { getToken, saveToken, token, admin, saveAdmin, setAdminInfo }
    },
    //持久化
    {
        persist: {
            //开启持久化
            enabled: true,
            //策略
            strategies: [
                {
                    //持久化key名称
                    key: 'admin-info',
                    //存储方式：localStorage或者sessionStorage
                    storage: localStorage,
                    //指定 state 中哪些数据需要被持久化。[] 表示不持久化任何状态，undefined 或 null 表示持久化整个 state
                    //paths: ['token']
                }
            ]
        }
    }
)